package util;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;

public class PinyinUtil {
	/**
	 * 获取中文字符串的拼音首字母缩写
	 */
	public static String getPinyin(String str) {
		StringBuilder sBuilder=new StringBuilder();
		//设置拼音的模板
		HanyuPinyinOutputFormat format=new HanyuPinyinOutputFormat();
		format.setCaseType(HanyuPinyinCaseType.UPPERCASE);//设置转化后的拼音为大写
		format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);//忽略语调
		for (int i = 0; i <str.length(); i++) {
			try {
				String[] pinyin = PinyinHelper.toHanyuPinyinStringArray(str.charAt(i),format);//获取汉语拼音
				String p=pinyin[0];//获取到每一个字的拼音
				
				sBuilder.append(p.charAt(0));
			} catch (BadHanyuPinyinOutputFormatCombination e) {
				//当字符创出现字幕是会出现异常
				sBuilder.append(str.charAt(i));
			}
		}
		return sBuilder.toString();
	}
}
